package com.jade.store.wechat.biz.service;

import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.cache.CacheService;
import com.jade.store.wechat.biz.common.Configure;
import com.jade.store.wechat.biz.common.Util;
import com.jade.store.wechat.biz.common.WxConstantUtil;
import com.jade.store.wechat.biz.protocol.auth.AuthorizerTokenReq;
import com.jade.store.wechat.biz.protocol.auth.AuthorizerTokenRes;
import com.jade.store.wechat.biz.service.auth.AuthorizerTokenService;
import com.jade.store.wechat.entity.WechatApp;
import com.jade.store.wechat.service.WechatAppFacade;

/**
 * 基础服务
 * User: jinya
 * Date: 2016/12/13
 * Time: 14:29
 * TEL :17701640710   MAIL:2009_jinya@163.com
 * To change this template use File | Settings | File Templates.
 */
public class BaseWxService  extends BaseService{
    private CacheService cacheService = ApplicationContextUtils.getBean("system_cacheService");
    private AuthorizerTokenService _authorizerTokenService;
    //API的地址
    private String apiURL;
    public BaseWxService(String appid,String api) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        super(api);
        _authorizerTokenService=new AuthorizerTokenService();
        try{
           String formatApi= String.format(api,getAuthroizerAccessToken(appid));
            super.setApiURL(formatApi);
        }catch (Exception e){
            System.out.print(e.toString());
        }
    }

    /**
     * 请求获取Token服务
     * @param
     * @return API返回的数据
     * @throws Exception
     */
    public String getAuthroizerAccessToken(String appid) throws Exception {
      //   Object obj=cacheService.get(WxConstantUtil.cache_wx_access_token+appid);
        // if(obj==null){
            WechatAppFacade wechatAppFacade = ApplicationContextUtils.getBean("WechatAppFacade");
            WechatApp wechatApp=wechatAppFacade.getLatestWechatAppByAppID(appid);
            if(wechatApp==null)   throw new Exception("请授权公众号");
            //if(wechatApp.getStatus()!=WechatApp.STATUS_NORMAL)throw new Exception("请重新授权公众号");
            AuthorizerTokenReq req=new AuthorizerTokenReq();
            req.setComponent_appid(Configure.appID);
            req.setAuthorizer_appid(appid);
            req.setAuthorizer_refresh_token(wechatApp.getAuthorizer_refresh_token());
            String responseString = _authorizerTokenService.sendJsonPost(req);
            AuthorizerTokenRes res = (AuthorizerTokenRes) Util.getObjectFromJson(responseString, AuthorizerTokenRes.class);
            cacheService.set(WxConstantUtil.cache_wx_access_token+appid, res.getAuthorizer_access_token(), 10000);
            return res.getAuthorizer_access_token();
      //  }else
        //    return obj.toString();
    }
}
